package org.example.mall.admin.configuration.auth.grant;

import cn.hutool.core.util.StrUtil;
import org.example.mall.admin.constant.auth.AuthTypeConst;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author hzq
 * @date 2021/12/6 10:49
 */
public class CustomTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "custom";

    private final AuthenticationManager authenticationManager;

    public CustomTokenGranter(AuthenticationManager authenticationManager,
                              AuthorizationServerTokenServices tokenServices,
                              ClientDetailsService clientDetailsService,
                              OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        // 处理器类型
        String handlerType = parameters.get(AuthTypeConst.HANDLER_TYPE);

        if (StrUtil.isBlank(handlerType)) {
            throw new InvalidRequestException("Missing handler type");
        }

        // 自定义 union_id 不支持外部登录
        // 只能用于内部 刷新token 检验token 使用
        if (handlerType.equals(AuthTypeConst.UNION_ID)) {
            throw new UnsupportedGrantTypeException("Unsupported handler type: " + handlerType);
        }

        // 标识
        String principal = parameters.get(AuthTypeConst.PRINCIPAL);
        // 凭证
        String credentials = parameters.get(AuthTypeConst.CREDENTIALS);
        // 预认证
        Authentication userAuth = new CustomAuthenticationToken(handlerType, principal, credentials);
        // 绑定参数详情
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        // 已认证
        userAuth = authenticationManager.authenticate(userAuth);
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
